import os
import json
import asyncio
from typing import Any, Dict

import httpx
from dotenv import load_dotenv
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
# import sys
# print("weather-mcp-py: starting...", file=sys.stderr, flush=True)

# 1) 强制无缓冲输出
os.environ["PYTHONUNBUFFERED"] = "1"

load_dotenv()
API_KEY = os.getenv("API_KEY")
if not API_KEY:
    raise RuntimeError("请在 .env 中配置 API_KEY")

# 创建 Server 实例
app = Server("weather-mcp-py", "1.0.0")

@app.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="get_weather",
            description="获取指定城市实时天气",
            inputSchema={
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名称，如 北京"}
                },
                "required": ["city"],
            },
        )
    ]

@app.call_tool()
async def call_tool(name: str, arguments: Dict[str, Any]) -> list[TextContent]:
    if name != "get_weather":
        raise ValueError(f"Unknown tool: {name}")

    city = arguments.get("city", "北京")
    params = {"key": API_KEY, "city": city}

    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.get(
            "http://apis.juhe.cn/simpleWeather/query",
            params=params,
        )
        if resp.status_code != 200:
            raise RuntimeError(f"接口返回 {resp.status_code}")

    data = resp.json()
    return [TextContent(type="text", text=json.dumps(data, ensure_ascii=False, indent=2))]

# ---------- 关键修复 ----------
async def main():
    # print("🚀 The Weather MCP server is started via stdio mode.")
    async with stdio_server() as (read_stream, write_stream):
        await app.run(read_stream, write_stream, app.create_initialization_options())

if __name__ == "__main__":
    asyncio.run(main()) 